﻿using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using RxxAdmin.Common;
using RxxAdmin.Common.Helper;
using Serilog;
using StackExchange.Profiling;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RxxAdmin.Extensions;
/// <summary>
/// MiniProfiler 性能分析启动服务
/// </summary>
public static class MiniProfilerSetup
{
    public static void AddMiniProfilerSetup(this IServiceCollection services) { 
        if(services == null) throw new ArgumentNullException(nameof(services));
        services.AddMemoryCache();
        if (AppSettings.Middleware.MiniProfiler.ObjToBool()) {
            services.AddMiniProfiler(options => {
                // 设定弹出窗口的位置是左下角
                options.PopupRenderPosition = RenderPosition.Left;
                // 设定在弹出的明细窗口里会显式Time With Children这列
                options.PopupShowTimeWithChildren = true;
                // 设定访问分析结果URL的路由基地址
                options.RouteBasePath = "/profiler";
            });
        }
    }

    public static void UseMiniProfilerMiddleware(this IApplicationBuilder app)
    {
        if (app == null) throw new ArgumentNullException(nameof(app));

        try
        {
            if (AppSettings.Middleware.MiniProfiler.ObjToBool())
            {
                // 性能分析
                app.UseMiniProfiler();
            }
        }
        catch (Exception e)
        {
            Log.Error($"An error was reported when starting the MiniProfilerMildd.\n{e.Message}");
            throw;
        }
    }
}
